﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using WebAppAuthAdmin.AuthApiManagementServiceReference;
using WebAppAuthAdmin.Code;
using Web.Framework;
using AuthApi.Contracts;
using WebAppAuthAdmin.Code.Security;

namespace WebAppAuthAdmin.App
{
    public partial class RoleEdit : BasePage
    {
        public RoleIncluded role
        {
            get
            {
                return (RoleIncluded)ViewState["role"];
            }
            set
            {
                ViewState["role"] = value;
            }
        }

        private WebApplicationInfo applicationInfo
        {
            get
            {
                return (WebApplicationInfo)ViewState["webApplicationInfo"];
            }
            set
            {
                ViewState["webApplicationInfo"] = value;
            }
        }

        private List<LinkButton> actionButtons = new List<LinkButton>();
        protected override void OnInit(EventArgs e)
        {
            base.OnInit(e);

            LinkButton crearContactoButton = new LinkButton();
            crearContactoButton.ID = "guardarButton";
            crearContactoButton.Text = "Guardar";
            crearContactoButton.Click += new EventHandler(lnkGuardar_Click);
            actionButtons.Add(crearContactoButton);

            base.LoadContextActions(actionButtons);
        }

        protected override void ApplySecurity()
        {
            bool hasPermission;
            if (role.Id == 0)
            {
                hasPermission = HasPermissionFor(AppSecurity.APP_ROLE_CREAR);
            }
            else
            {
                hasPermission = HasPermissionFor(AppSecurity.APP_ROLE_EDITAR);
            }

            hasPermission = hasPermission && HasPermissionFor(AppSecurity.APP_USERS_SETPERMISSION_ + applicationInfo.Id.ToString());

            actionButtons.Where(a => a.ID == "guardarButton").Single().Visible = hasPermission;
            this.lnkGuardar.Visible = hasPermission; 
        }

        protected void Page_Load(object sender, EventArgs e)
        {
            try
            {
                HasPermissionToSeeMe(AppSecurity.APP_ROLE_VIEW);
                if (!this.IsPostBack)
                {
                    if (this.Request.QueryString["applicationId"] != null)
                    {
                        applicationInfo = WebServiceHelper.GetApplicationById(Convert.ToInt32(this.Request.QueryString["applicationId"]));

                        if (String.IsNullOrEmpty(this.Request.QueryString["Id"]))
                        {
                            // Nuevo rol
                            this.role = new RoleIncluded();
                            this.role.Operations = WebServiceHelper.GetOperationsForApplication(applicationInfo.Id);
                        }
                        else
                        {
                            int roleId = Convert.ToInt32(this.Request.QueryString["Id"]);
                            this.role = WebServiceHelper.GetRoleForApplicationById(applicationInfo.Id, roleId);
                        }

                        Bind();
                    }                  
                    else
                    {
                        ExceptionManager.Instance.ShowWarning("No se proporcionó el paramtro aplicación o rol");
                    }                   
                }
            }
            catch (Exception ex)
            {
                ExceptionManager.Instance.HandleException(ex);
            }
        }

        private const int rowOperaciones = 3;
        protected void Grid_RowDataBound(object sender, GridViewRowEventArgs e)
        {
            try
            {
                if (e.Row.RowType == DataControlRowType.DataRow)
                {
                    OperationIncluded operation = (OperationIncluded)e.Row.DataItem;

                    CheckBox chkSelect = (CheckBox)e.Row.Cells[0].FindControl("chkSelectRow");
                    chkSelect.Checked = operation.IsIncluded;
                    if (operation.IsIncluded)
                    {
                        this.hidCheckedRows.Value += string.Format("#{0}#", operation.Id);
                    }

                    LinkButton lnkRowVerOperaciones = (LinkButton)e.Row.Cells[rowOperaciones].FindControl("lnkRowVerOperaciones");
                    lnkRowVerOperaciones.CommandArgument = e.Row.RowIndex.ToString();
                }
            }
            catch (Exception ex)
            {
                ExceptionManager.Instance.HandleException(ex);
            }
        }

        protected void Grid_RowCommand(object sender, GridViewCommandEventArgs e)
        {
            try
            {
                if (e.CommandName == "verroles")
                {
                    int operationId = Convert.ToInt32(this.Grid.DataKeys[Convert.ToInt32(e.CommandArgument)].Value);
                    this.Response.Redirect(string.Format("/App/OperationViewRoles.aspx?Id={0}", operationId, true));
                }
            }
            catch (Exception ex)
            {
                ExceptionManager.Instance.HandleException(ex);
            }
        }

        private void Bind()
        {
            this.txtAplicacion.Text = applicationInfo.Name;
            this.txtRoleName.Text = role.Name;

            this.Grid.DataSource = this.role.Operations;
            this.Grid.DataBind();
        }

        private void Validar()
        {
            // TODO
        }

        private void SetData()
        {
            this.role.ApplicationId = applicationInfo.Id;
            role.Name = this.txtRoleName.Text;

            List<int> selectedRowsIds = UIHelper.GetSelectedRowIds(this.hidCheckedRows.Value);

            foreach (var operation in this.role.Operations)
            {
                if (selectedRowsIds.Contains(operation.Id))
                {
                    operation.IsIncluded = true;
                }
                else
                {
                    operation.IsIncluded = false;
                }
            }

            this.hidCheckedRows.Value = string.Empty;
        }

        private void Save()
        {
            this.role = WebServiceHelper.SaveRole(this.role);
        }

        protected void lnkGuardar_Click(object sender, EventArgs e)
        {
            try
            {
                Validar();
                SetData();
                Save();
                Response.Redirect(string.Format("/App/ApplicationEdit.aspx?Id={0}", applicationInfo.Id), true);
            }
            catch (Exception ex)
            {
                ExceptionManager.Instance.HandleException(ex);
            }
        }
    }
}